#include<iostream>
#include"log.hpp"
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string>
#include<cstring>
int main(int argc,char* argv[])//./clent 121.0.0.1 8080
{
    if(argc!=3)
    {
        LOG(FATAL)<<"Usage:./client ip port";
        return 1;
    }
    uint16_t port=std::stoi(argv[2]);
    std::string ip=argv[1];

    //创建socket
    int sockfd=::socket(AF_INET,SOCK_STREAM,0);
    //设置地址
    struct sockaddr_in addr;
    memset(&addr,0,sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_port=::htons(port);
    addr.sin_addr.s_addr=::inet_addr(ip.c_str());
    //连接服务器
    int ret=::connect(sockfd,(struct sockaddr*)&addr,sizeof(addr));
    if(ret==-1)
    {
        LOG(FATAL)<<strerror(errno);
        return 2;
    }
    while(true)
    {
        //向服务器发送数据
        std::string send_message;
        std::cout<<"client #";
        std::getline(std::cin,send_message);

        write(sockfd,send_message.c_str(),send_message.size());
        //接收服务器数据
        char recv_buf[1024];
        int n=read(sockfd,recv_buf,sizeof(recv_buf)-1);
        if(n==0) break;
        recv_buf[n]=0;
        std::cout<<recv_buf<<std::endl;
    }
    //关闭socket
    close(sockfd);
    return 0;
}
